package com.example.EurekaConsumer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;

@RestController
public class HelloController {
	
	@Autowired
	//spring自己抽象出来的接口
	DiscoveryClient client;
	
	//eureka自己实现的client
	@Autowired
	EurekaClient client2;
	
	
	@Autowired
	LoadBalancerClient lb;
	
	@GetMapping("/hello")
	public String hello() {
		
		return "hello-consumer";
	}
	
	
	//获取所有注册到eureka的服务
	@GetMapping("/client")
	public String client() {
		List<String> services = client.getServices();
		
		return JSONObject.toJSONString(services);
	}
	

	//获取某个服务实例的服务列表
	@GetMapping("/client2")
	public String client2() {
		List<ServiceInstance> instances = client.getInstances("provider");
		
		return JSONObject.toJSONString(instances);
	}
	
	
	@GetMapping("/client3")
	public String client3(String id) {
		//instanceId 如：DESKTOP-R4DOSGR:provider:81
		List<InstanceInfo> instancesById = client2.getInstancesById(id);
		
		return JSONObject.toJSONString(instancesById);
	}
	
	@GetMapping("/client4")
	public String client4() {
		//使用服务名找列表
		List<InstanceInfo> apps = client2.getInstancesByVipAddress("provider", false);
		InstanceInfo instanceInfo = apps.get(0);
		String url = "http://" + instanceInfo.getHostName() + ":" + instanceInfo.getPort() + "/hello";
		
		RestTemplate restTemplate = new RestTemplate();
		String forObject = restTemplate.getForObject(url, String.class);
		return url + ":" +forObject;
	}
	
	//使用负载均衡获取可用的服务列表-ribbon
	@GetMapping("/client5")
	public String client5() {
		
		ServiceInstance choose = lb.choose("provider");
		String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/hello";
		
		RestTemplate restTemplate = new RestTemplate();
		String forObject = restTemplate.getForObject(url, String.class);
		return url + ":" + forObject;
	}
	
	@GetMapping("/client6")
	public Object client6(String name,String id) {
		
		ServiceInstance choose = lb.choose("provider");
		String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/postObj";
		
		RestTemplate restTemplate = new RestTemplate();
		Map<String,String> param = new HashMap<String,String>();
		param.put("name", name);
		param.put("id", id);
		Map postForObject = restTemplate.postForObject(url, param, Map.class);
		return url + ":" + postForObject;
	}
}
